import React, { Component } from 'react';

class EventEmitter {
  listeners = {};

  on(event: string | number, func: any) {
    const events = this.listeners[event];
    if (events) {
      events.push(func);
    } else {
      this.listeners[event] = [func];
    }
  }

  emit(event: string | number, arg: any) {
    const events = this.listeners[event];
    if (events) {
      events.forEach((item: (arg0: any) => void) => {
        item(arg);
      });
    }
  }

  off(event: string | number, func: any) {
    const events = this.listeners[event];
    if (!events) {
      return;
    }
    const index = events.indexOf(func);
    if (index !== -1) {
      events.splice(index, 1);
    }
  }

  once(event: any, func: any) {
    const context = this;
    this.on(event, function () {
      func.apply(context, arguments);
      context.off(event, func);
    });
  }
}

export default EventEmitter;
